package spring;


import org.springframework.core.io.Resource;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * author:xiaobo
 * date: 2016/7/29.
 */
public class WebPointLoad {


    static UUIDResourcesHandler resourcesHandler = new UUIDResourcesHandler();



    /**
     * web下载视屏文件  ，支持断点下载
     *
     * @param response
     * @param request
     * @param resource
     * @param type
     * @throws IOException
     */
    public static void pointLoad(HttpServletResponse response, HttpServletRequest request, final File resource, final String type) throws IOException, ServletException {

        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        if(null == path){
            request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE,"sdf");
        }

        resourcesHandler.setResourceResolvers(new ArrayList<ResourceResolver>(){{
            add(new ResourceResolver() {
                public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
                    UUIDFileResource res = new UUIDFileResource(resource,resource.getName());
                    res.setMimeType(type);
                    return res;
                }
                public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) {
                    return resourcePath;
                }
            });
        }});


        resourcesHandler.handleRequest(request,response);
    }



















}
